<template>
  <div class="profile-view">
    <div class="header">
      <h2>个人信息</h2>
    </div>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="profile-form"
    >
      <!-- 基本信息 -->
      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>

        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            accept="image/*"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadAvatar"
          >
            <el-avatar
              v-if="formData.avatar"
              :size="100"
              :src="formData.avatar"
            />
            <el-icon v-else class="avatar-uploader-icon" :size="30">
              <plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" disabled />
        </el-form-item>
      </el-card>

      <!-- 修改密码 -->
      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span>修改密码</span>
          </div>
        </template>

        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="formData.currentPassword"
            type="password"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="formData.newPassword"
            type="password"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-card>

      <!-- 保存按钮 -->
      <div class="form-actions">
        <el-button type="primary" :loading="saving" @click="save">
          保存修改
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const formRef = ref<FormInstance>()
const saving = ref(false)

// 表单数据
const formData = ref({
  avatar: '',
  username: '',
  email: '',
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const getUserInfo = async () => {
  try {
    const response = await fetch('/api/users/me')
    const data = await response.json()
    formData.value.avatar = data.avatar
    formData.value.username = data.username
    formData.value.email = data.email
  } catch (error) {
    console.error('Failed to get user info:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB')
    return false
  }
  return true
}

// 上传头像
const uploadAvatar = async (options: any) => {
  try {
    const formData = new FormData()
    formData.append('avatar', options.file)

    const response = await fetch('/api/users/avatar', {
      method: 'POST',
      body: formData
    })
    const data = await response.json()
    formData.value.avatar = data.avatar
    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('Failed to upload avatar:', error)
    ElMessage.error('头像上传失败')
  }
}

// 保存修改
const save = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true

    const response = await fetch('/api/users/me', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: formData.value.username,
        currentPassword: formData.value.currentPassword,
        newPassword: formData.value.newPassword
      })
    })

    if (!response.ok) {
      throw new Error('保存失败')
    }

    ElMessage.success('保存成功')
    formData.value.currentPassword = ''
    formData.value.newPassword = ''
    formData.value.confirmPassword = ''
  } catch (error: any) {
    console.error('Failed to save profile:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// 初始化
onMounted(() => {
  getUserInfo()
})
</script>

<style scoped lang="scss">
.profile-view {
  padding: 24px;

  .header {
    margin-bottom: 24px;

    h2 {
      margin: 0;
    }
  }

  .profile-form {
    max-width: 600px;

    .mb-4 {
      margin-bottom: 24px;
    }

    .avatar-uploader {
      :deep(.el-upload) {
        border: 1px dashed var(--el-border-color);
        border-radius: 50%;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration);

        &:hover {
          border-color: var(--el-color-primary);
        }
      }

      .avatar-uploader-icon {
        width: 100px;
        height: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: var(--el-text-color-secondary);
      }
    }

    .form-actions {
      margin-top: 24px;
      text-align: right;
    }
  }
}
</style> 